/*****************************************************************************
 * Product: 数据同步解决方案                                                    
 * Copyright (C) 2010-2011  瑞科软件. All Rights Reserved.                                                                       *
 * 改程序是开源的，您可以修改源代码，做二次开发，定制您自己的同步程序                     
 * 您可以通过我们的网站了解详细信息，包括安装与使用指南，  http://www.ruike.org         
 * 																		      			
 *****************************************************************************/
package com.service;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.mk.HibernateException;
import org.mk.type.MySQLTypeFactory;
import org.mk.type.Type;
import com.client.RecordCreateService;
import com.db.ColumnInfoBean;
import com.db.connection.DBCPPostgresManager;
import com.db.domain.Communication;
import com.excel.read.Config;
import com.excel.read.DBTable;
import com.operation.OperationMap;
import com.operation.POXML;
import com.xml.RecordExtract;

/**
 * 
 * @功能 客户端通信服务,单线程处理
 * @author 张华
 * @date May 23, 2009
 * @version 1.0 May 23, 2009 11:02:31 AM
 */
public class CommunicationService implements Runnable {
	public static Log log = LogFactory.getLog(CommunicationService.class);
	public String getRecordText(OperationMap opMap, com.xml.Record record)
			throws HibernateException, SQLException {

		String xml = "";
		Connection conn = null;
		PreparedStatement pstmt = null;
		ResultSet rs = null;
		ResultSet res = null;
		try {
			conn = DBCPPostgresManager.getConnection();
			DBTable dbTable = (DBTable) Config.allTable.get(record
					.getTableName());
			List<ColumnInfoBean> cinfoNameList = dbTable.getColumnInfos();
			List<String> selfNameList = new ArrayList<String>();
			for (ColumnInfoBean cinfo : cinfoNameList) {
				selfNameList.add(cinfo.getName());
			}
			String sql = dbTable.getSelectSQL();
			ColumnInfoBean pk = dbTable.getPk();
			// 执行SQL语句
			pstmt = conn.prepareStatement(sql);
			Type atype = MySQLTypeFactory.basic(pk.getNoPresitionTypeName());
			Object value = record.fieldMap.get(pk.getName().toUpperCase());
			atype.nullSafeSet(pstmt, value, 1);
			rs = pstmt.executeQuery();
			if (rs.next()) {
				xml = POXML.getXML(dbTable, rs);
			}
		} catch (Exception e) {
			log.error("Error getRecordText: " + e.toString());
		} finally {
			DBCPPostgresManager.close(conn, pstmt, rs);

		}
		return xml;
	}

	/**
	 * @功能 取得请求并且处理
	 * @param requestList
	 * @param conn
	 * @throws Exception
	 * @date May 23, 2009
	 */
	public void doResponse(List<Communication> requestList) throws Exception {
		for (Communication aCommunication : requestList) {
			RecordExtract aRecordExtract = new RecordExtract();
			OperationMap aOperationMap = (OperationMap)aRecordExtract.extractOperationMap(
					aCommunication.request, aCommunication.clientFrom);
			List<OperationMap> list = new ArrayList<OperationMap>();
			list.add(aOperationMap);
			String response = getRecordText(aOperationMap, aOperationMap.record);
			aCommunication.setResponse(response);
		}

	}

	public void run() {

		while (true) {
			try {
				// 取得Communication请求并处理
				CCService aCCService = SyncServiceFactory.getCCService();
				List<Communication> requestList = aCCService
						.getRequest(RecordCreateService.orgid);				
				doResponse(requestList);
				// 将响应送回服务器
				aCCService.doResponse(requestList);
			} catch (SQLException e1) {
				String str = e1.toString();
				log.error(str);
			} catch (Exception e) {
				e.printStackTrace();
			}

			try {
				Thread.currentThread().sleep(5000);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}

		}

	}

}
